<?php

namespace addons\qingdong\model;

use think\Db;
use think\Exception;
use think\Model;
use traits\model\SoftDelete;

/**
 * 表单
 */
class Form extends Model {
    use SoftDelete;

    const LEADS_TYPE = 'leads';
    const CUSTOMER_TYPE = 'customer';
    const CONTACTS_TYPE = 'contacts';
    const CONTRACT_TYPE = 'contract';
    const RECEIVABLES_TYPE = 'examine';
    const BUSINESS_TYPE = 'business';
    const SIGNIN_TYPE = 'signin';

	// 表名,不含前缀
	protected $name = 'qingdong_form';
	// 自动写入时间戳字段
	protected $autoWriteTimestamp = 'int';
	// 定义时间戳字段名
	protected $createTime = 'createtime';
	protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

	public function getUpdatetimeAttr($value){
		return date('Y-m-d H:i',$value);
	}

	public static function getDataValue($type,$info=[]){
		$data=self::where(['type'=>$type])->value('data');
		if($data){
		    $form = json_decode($data,true)['data'];
            foreach($form as $k=>$v){
                $form[$k]['data_value'] ='';
                if($info){
                    $form[$k]['data_value'] = isset($info[$v['id']]) ? $info[$v['id']] : '';
                    if(array_key_exists($v['id'],$info) && isset($info[$v['id']])){
                        if($v['component'] == 'select'){
                            if(isset($v['config']['multiple']) &&  $v['config']['multiple'] == true){
                                if(is_array($info[$v['id']])){
                                    $selectArrInfo = [];
                                    foreach($info[$v['id']] as $ks=>$vs){
                                        $selectArrInfo[$vs] = $vs;
                                    }
                                    $form[$k]['data_value'] = $selectArrInfo;
                                }else{
                                    $selectArr = explode(',',$info[$v['id']]);
                                    $selectArrInfo = [];
                                    foreach($selectArr as $ks=>$vs){
                                        $selectArrInfo[$vs] = $vs;
                                    }
                                    $form[$k]['data_value'] = $selectArrInfo;
                                }

                            }
                        }
                    }
                }
            }
			return $form;
		}else{
			return [];
		}
	}


    public static function getDataDetail($type,$params)
    {
        $form = Form::getDataValue($type);
        foreach($form as $k=>$v){
            if($v['component'] == 'uploadImage' || $v['component'] == 'uploadFile'){
                $params[$v['id'].'_str'] = NULL;
                if(key_exists($v['id'],$params)){

                    if(isset($params[$v['id']]) && $params[$v['id']]){
                        $whereT['id'] = array('in',$params[$v['id']]);
                        $fileinfo = File::where($whereT)->field('id,name,file_path,save_name')->select();
                        $fileinfo=collection($fileinfo)->toArray();
                        $params[$v['id']] = $fileinfo;

                        if($fileinfo){
                            $fileinfodata = '';
                            foreach($fileinfo as $kss=>$vss){
                                $fileinfodata = $vss['save_name'].','.$fileinfodata;
                            }
                            $params[$v['id'].'_str'] = rtrim($fileinfodata,',')?:NULL;
                        }
                    }
                }
            }

        }
        return $params;
    }

	/**
	 *获取form表单的NameID
	 */
	public static function getFromNameId($type){
		$data=self::getDataValue($type);
		$result=[];
		foreach ($data as $v){
			$result[$v['config']['label']]=$v['id'];
		}
		return $result;
	}

    /**
     * 更新提交表单内容
     * @param $type string 类型
     * @param $params array 提交内容
     * @return mixed
     */
    public static function updateFormParams($type, $params)
    {
        $form = Form::getDataValue($type);
        foreach ($form as $k => $v) {
            if ($v['component'] == 'uploadImage' || $v['component'] == 'uploadFile') {
                if (key_exists($v['id'], $params)) {
                    if ($params[$v['id']]) {
                        $filearr = explode(',', $params[$v['id']]);
                        $files = '';
                        if ($filearr) {
                            foreach ($filearr as $ks => $vs) {
                                $files = File::where(array('file_path|id' => $vs))
                                        ->order('id desc')->value('id') . ',' . $files;
                            }
                            $params[$v['id']] = rtrim($files, ',');
                        }
                    }
                }
            } elseif ($v['component'] == 'select') {
                if (isset($v['config']['multiple']) && $v['config']['multiple'] == true) {
                    if (key_exists($v['id'], $params)) {
                        if ($params[$v['id']]) {
                            $params[$v['id']] = implode(',', $params[$v['id']]);
                        }
                    }
                }
            } elseif ($v['component'] == 'checkbox') {
                if(isset($params[$v['id']])){
                    $params[$v['id']] = implode(',', $params[$v['id']]);
                }
            }
        }
        return $params;
    }

    /**
     * 获取model
     * @param $type
     * @return Contacts|Contract|Customer|Leads|Receivables
     */
    public function getTypeModel($type){

        switch ($type){
            case 'leads'://线索
                $model=new Leads();
                break;
            case 'customer'://客户
                $model=new Customer();
                break;
            case 'contract'://合同
                $model=new Contract();
                break;
            case 'contacts'://联系人
                $model=new Contacts();
                break;
            case 'examine'://回款
            case 'receivabels'://回款
                $model=new Receivables();
                break;
            case self::BUSINESS_TYPE://回款
                $model=new Business();
                break;
            default:
                $model=NULL;

        }
        return $model;
    }

    /**
     * 更新表单
     */
    public  function updateForm($id, $data)
    {
        $row = self::get($id);
        $fields     = json_decode($data, true);

        (new Field())->setFormField($row['type'], $fields['data']);
        $insertFormField = [];
        $model=$this->getTypeModel($row['type']);
        if(!empty($model)){
            $tableFields=$model->getTableFields();
        }
        $addParams=[];
        $updateParams=[];
        foreach ($fields['data'] as $k => &$d) {
            if(isset($d['showInfoType'])){
                unset($d['showInfoType']);
            }
            $content = $d['config']['content'] ?? [];
            $label = [];
            foreach ($content as $c) {
                if (isset($c['label'])) {
                    $label[] = $c['label'];
                } else {
                    $label[] = $c['value'];
                }
            }
            $name = $d['config']['label'] ?? '';
            $infoType = isset($d['config']['infoType']) ? $d['config']['infoType'] : 'additional';// additional附加信息 main 主要信息
            if ($infoType == 'main' && !empty($model)) {
                if (!in_array($d['id'], $tableFields)) {
                    $addParams[] = $d;
                } else {
                    $updateParams[] = $d;
                }
                
            }
            $value = $d['config']['value'] ?? '';
            if (is_array($value)) {
                $value = implode(',', $value);
            }
            $insertFormField[] = [
                'types' => $row['type'],
                'types_id' => 0,//分类ID（审批等）
                'field' => $d['id'],//字段名
                'name' => $name,//标识名
                'form_type' => $d['component'],//字段类型
                'default_value' => $value,//默认值
                'is_unique' => isset($d['config']['only']) ? ($d['config']['only'] ? 1 : 0) : '',//是否唯一
                'is_null' => ($d['config']['required'] ?? NULL) ? 1 : 0,//是否必填
                'input_tips' => $d['config']['placeholder'] ?? '',//提示文字
                'setting' => implode('|', $label),//设置
                'order_id' => $k,//排序ID
                'info_type' =>  $infoType,//信息类型
                'operating' => $d['config']['is_delete'] ? 0 : 3,//0改删，1改，2删，3无
                'list_show' => isset($d['config']['listShow']) ? ($d['config']['listShow'] ? 1 : 0) :0,//列表显示(1是，0否)
                'add_show' => isset($d['config']['addShow']) ? ($d['config']['addShow'] ? 1 : 0) :0,//添加显示(1是，0否)
                'createtime' => time(),
                'updatetime' => time()
            ];
        }

        $errorMessage = [];
        //新增
        if ($addParams) {
            if (! $this->createData($row['type'], $addParams)) {
                $errorMessage[] = $this->getError();
            }
        }
        //编辑
        if ($updateParams) {
            if (! $this->updateData($row['type'],$updateParams)) {
                $errorMessage[] = $this->getError();
            }
        }
        if ($errorMessage) {
            throw new Exception(implode(';', $errorMessage));
        }
        $formFieldModel = new FormField();
        $formFieldModel->where(['types'=>$row['type']])->delete();
        if(!$formFieldModel->allowField(true)->saveAll($insertFormField)){
            throw new Exception('添加表单字段失败');
        }

        return (new self())->save(['data' => json_encode($fields,JSON_UNESCAPED_UNICODE)], ['id' => $id]);
    }

    /**
     * 创建字段
     */
    public  function createData($types, $param){
        $model=$this->getTypeModel($types);
        $tablename=$model->getTable();
        $maxlength = '255';
        $defaultvalue = "DEFAULT NULL";
        //根据字段类型，创建字段

        $error_message=[];
        foreach ($param as $d){
            $default_value = $d['config']['value'] ?? '';
            if (is_array($default_value)) {
                $default_value = implode(',', $default_value);
            }
            
            $name= $d['config']['label'] ?? '';
            switch ($d['component']) {
                case 'Rate' ://评分
                case 'input' ://输入框
                case 'Cascader' ://区域选择框
                    $queryStr = "ALTER TABLE `" . $tablename . "` ADD COLUMN `".$d['id']."` VARCHAR( 255 ) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci  DEFAULT '' COMMENT '".$name."'";
                    break;
                case 'radio' ://单选框
                case 'select' ://下拉选择框
                case 'checkbox' ://多选框
                    $defaultvalue = $default_value ? "DEFAULT '".$default_value."'" : '';
                    $queryStr = "ALTER TABLE `" . $tablename . "` ADD COLUMN  `".$d['id']."` VARCHAR( ".$maxlength." ) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci ".$defaultvalue." COMMENT '".$name."'";
                    break;
                case 'textarea' ://文本框
                    $queryStr = "ALTER TABLE `" . $tablename . "` ADD COLUMN  `".$d['id']."`  TEXT COMMENT '".$name."'";
                    break;
                case 'input-number' ://数字框
                    $defaultvalue = abs(intval($default_value)) > 2147483647 ? 2147483647 : intval($default_value);
                    $maxlength = 18;
                    $queryStr = "ALTER TABLE `" . $tablename . "` ADD COLUMN `".$d['id']."`int(11) DEFAULT '".$defaultvalue."' COMMENT '".$name."'";
                    break;
                case 'DatePicker' ://日期选择框
                    $queryStr = "ALTER TABLE `" . $tablename . "` ADD COLUMN `".$d['id']."` DATE ".$defaultvalue." COMMENT '".$name."'";
                    break;
                case 'TimePicker' ://时间选择框
                    $defaultvalue = "DEFAULT NULL";
                    $queryStr = "ALTER TABLE `" . $tablename . "` ADD COLUMN `".$d['id']."` DATETIME ".$defaultvalue." COMMENT '".$name."'";
                    break;
                case 'uploadImage' ://图片上传
                case 'uploadFile' ://文件上传
                    $queryStr = "ALTER TABLE `" . $tablename . "` ADD COLUMN `".$d['id']."` VARCHAR ( ".$maxlength." ) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci COMMENT '".$name."' ";
                    break;
                default :
                    $maxlength = 255;
                    $queryStr = "ALTER TABLE `" . $tablename . "` ADD COLUMN `".$d['id']."` VARCHAR( ".$maxlength." ) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci ".$defaultvalue." COMMENT '".$name."'";
                    break;
            }
            $resData = Db::execute($queryStr);
            if ($resData === false) {
                $this->where(['field_id' => $this->field_id])->delete();
                $error_message[] = $name.',添加失败';
            }
        }
        if ($error_message) {
            $this->error = implode(';',$error_message);
            return false;
        }
        return true;
    }

    /**
     * 修改字段
     */
    public function updateData($types, $param)
    {
        $model=$this->getTypeModel($types);
        $tablename = $model->getTable();
        $maxlength = '255';
        $defaultvalue = "DEFAULT NULL";
        //根据字段类型，创建字段
        $error_message=[];
        foreach ($param as $d) {
            $default_value = $d['config']['value'] ?? '';
            if (is_array($default_value)) {
                $default_value = implode(',', $default_value);
            }
            $name = $d['config']['label'] ?? '';
            switch ($d['component']) {
                case 'Rate' ://评分
                case 'input' ://输入框
                case 'Cascader' ://区域选择框
                    $queryStr = "ALTER TABLE `" . $tablename . "` MODIFY COLUMN `" . $d['id'] . "` VARCHAR( 255 ) COMMENT '" . $name . "'";
                    break;
                case 'radio' ://单选框
                case 'select' ://下拉选择框
                case 'checkbox' ://多选框
                    $defaultvalue = $default_value ? "DEFAULT '" . $default_value . "'" : '';
                    $queryStr = "ALTER TABLE `" . $tablename . "` MODIFY COLUMN  `" . $d['id'] . "` VARCHAR( " . $maxlength . " )  " . $defaultvalue . " COMMENT '" . $name . "'";
                    break;
                case 'textarea' ://文本框
                    $queryStr = "ALTER TABLE `" . $tablename . "` MODIFY COLUMN  `" . $d['id'] . "`  TEXT COMMENT '" . $name . "'";
                    break;
                case 'input-number' ://数字框
                    $defaultvalue = abs(intval($default_value)) > 2147483647 ? 2147483647 : intval($default_value);
                    $maxlength = 18;
                    $queryStr = "ALTER TABLE `" . $tablename . "` MODIFY COLUMN `" . $d['id'] . "`decimal(" . $maxlength . ",2) DEFAULT '" . $defaultvalue . "' COMMENT '" . $name . "'";
                    break;
                case 'DatePicker' ://日期选择框
                    $queryStr = "ALTER TABLE `" . $tablename . "` MODIFY COLUMN `" . $d['id'] . "` DATE " . $defaultvalue . " COMMENT '" . $name . "'";
                    break;
                case 'TimePicker' ://时间选择框
                    $defaultvalue = "DEFAULT NULL";
                    $queryStr = "ALTER TABLE `" . $tablename . "` MODIFY COLUMN `" . $d['id'] . "` DATETIME " . $defaultvalue . " COMMENT '" . $name . "'";
                    break;
                case 'uploadImage' ://图片上传
                case 'uploadFile' ://文件上传
                    $queryStr = "ALTER TABLE `" . $tablename . "` MODIFY COLUMN `" . $d['id'] . "` VARCHAR ( " . $maxlength . " )  COMMENT '" . $name . "' ";
                    break;
                default :
                    $maxlength = 255;
                    $queryStr = "ALTER TABLE `" . $tablename . "` MODIFY COLUMN `" . $d['id'] . "` VARCHAR( " . $maxlength . " )  COMMENT '" . $name . "'";
                    break;
            }
            $resData = Db::execute($queryStr);
            if ($resData === false) {
                $this->where(['field_id' => $this->field_id])->delete();
                $error_message[] = $name . ',添加失败';
            }
        }
        if ($error_message) {
            $this->error = implode(';', $error_message);
            return false;
        }
        return true;
    }
}
